#!/usr/bin/python

import matplotlib.pyplot as plt, sqlite3, sys, numpy as np, datetime

def graphall(val, start, end, split,db):
	"""
	The following does math to take the date out of the crazy format that is while in
	the database (YYDDDHHMM) and changes it into something that makes sense to people
	(HH:MM DD/mm/YYYY) for the graphs, storing it in the string timeinterval.
	"""
	montharray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
	monthstart = 0
	monthend = 0

	yearstart = start / 10000000 + 2000
	yearend = end / 10000000 + 2000
	daystart = (start - (start / 10000000) * 10000000)  / 10000
	dayend = (end - (end / 10000000) * 10000000)  / 10000
	hourstart = (start - (start / 10000) * 10000)  / 100
	hourend = (end - (end / 10000) * 10000)  / 100
	minutestart = (start - (start / 100) * 100)
	minuteend = (end - (end / 100) * 100)

	while (daystart - montharray[monthstart] > 0):
		daystart = daystart - montharray[monthstart]
		monthstart += 1
	monthstart += 1

	while (dayend - montharray[monthend] > 0):
		dayend = dayend - montharray[monthend]
		monthend += 1
	monthend += 1

	# The final product, a string saying the time interval
	timeinterval = "from " + str(hourstart) + ":" + str(minutestart) + " on " + str(monthstart) + "/" + str(daystart) + "/" + str(yearstart) + " to " + str(hourend) + ":" + str(minuteend) + " on " + str(monthend) + "/" + str(dayend) + "/" + str(yearend)

	# Creating all the graphs
	followers_vs_influence(timeinterval, start, end, split,db)
	time_vs_post_and_influence(timeinterval, start, end, split,db)
	total_num_of_posts(timeinterval, start, end, split, db)

def total_num_of_posts(timeinterval, start, end, split, db):
	x = [0]
	conn = sqlite3.connect(db)
	c = conn.cursor()
	c.execute('select * from userdata where datetime > ? and datetime < ?', (start, end))

	if split == "minute":
		for entry in c:
			yeardif = entry[3] / 10000000 - entry[3] / 10000000
			daydif = (entry[3] - (entry[3] / 10000000) * 10000000)  / 10000 - (start - (start / 10000000) * 10000000)  / 10000
			hourdif = (entry[3] - (entry[3] / 10000) * 10000)  / 100 - (start - (start / 10000) * 10000)  / 100
			mindif = (entry[3] - (entry[3] / 100) * 100) - (start - (start / 100) * 100)
			index = mindif + 60 * hourdif + 60 * 24 * daydif + 60 * 24 * 365 * yeardif
			while (len(x) <= index):
				x.append(0)
			x[index] += 1
	elif split == "hour":
		for entry in c:
			yeardif = entry[3] / 10000000 - entry[3] / 10000000
			daydif = (entry[3] - (entry[3] / 10000000) * 10000000)  / 10000 - (start - (start / 10000000) * 10000000)  / 10000
			hourdif = (entry[3] - (entry[3] / 10000) * 10000)  / 100 - (start - (start / 10000) * 10000)  / 100
			index = hourdif + 24 * daydif + 24 * 365 * yeardif
			while (len(x) <= index):
				x.append(0)
			x[index] += 1
	elif split == "day":
		for entry in c:
			yeardif = entry[3] / 10000000 - entry[3] / 10000000
			daydif = (entry[3] - (entry[3] / 10000000) * 10000000)  / 10000 - (start - (start / 10000000) * 10000000)  / 10000
			index = daydif + 365 * yeardif
			while (len(x) <= index):
				x.append(0)
			x[index] += 1
	elif split == "month":
			yeardif = entry[3] / 10000000 - entry[3] / 10000000
			index = 365 * yeardif / 12;
			while (len(x) <= index):
				x.append(0)
			x[index] += 1
	elif split == "year":
		for entry in c:
			yeardif = entry[3] / 10000000 - entry[3] / 10000000
			index = yeardif;
			while (len(x) <= index):
				x.append(0)
			x[index] += 1
			plt.xlabel('Time (in ' + split + 's) from ')

	plt.plot(x, '-')
	plt.title('Post Count Over Time')
	plt.ylabel('Number of posts')
	plt.xlabel('Time (in ' + split + 's) ' + timeinterval)
	plt.savefig("post_count_vs_time.png", format="png")
	plt.clf()
	c.close()

def followers_vs_influence(timeinterval, start, end, split,db):
	x = []
	y = []
	conn = sqlite3.connect(db)
	c = conn.cursor()
	c.execute('select * from userdata where datetime > ? and datetime < ?', (start, end))
	for entry in c:
		x.append(entry[2])
		y.append(entry[4])
	plt.plot(x, y, 'ro')
	plt.title('Post Rating vs. Influence')
	plt.ylabel('Post Rating')
	plt.xlabel('Influence (Number of followers/friends)')
	plt.savefig("followers_vs_influence.png", format="png")
	plt.clf()
	c.close()

def time_vs_post_and_influence(timeinterval, start, end, split,db):
	x = [0]
	conn = sqlite3.connect(db)
	c = conn.cursor()
	c.execute('select * from userdata where datetime > ? and datetime < ? order by datetime', (start, end))
	assist = 0

	if split == "minute":
		for entry in c:
			yeardif = entry[3] / 10000000 - entry[3] / 10000000
			daydif = (entry[3] - (entry[3] / 10000000) * 10000000)  / 10000 - (start - (start / 10000000) * 10000000)  / 10000
			hourdif = (entry[3] - (entry[3] / 10000) * 10000)  / 100 - (start - (start / 10000) * 10000)  / 100
			mindif = (entry[3] - (entry[3] / 100) * 100) - (start - (start / 100) * 100)
			index = mindif + 60 * hourdif + 60 * 24 * daydif + 60 * 24 * 365 * yeardif
			while (len(x) <= index):
				x.append(0)
			x[index] += entry[4] * entry[2]
	elif split == "hour":
		for entry in c:
			yeardif = entry[3] / 10000000 - entry[3] / 10000000
			daydif = (entry[3] - (entry[3] / 10000000) * 10000000)  / 10000 - (start - (start / 10000000) * 10000000)  / 10000
			hourdif = (entry[3] - (entry[3] / 10000) * 10000)  / 100 - (start - (start / 10000) * 10000)  / 100
			index = hourdif + 24 * daydif + 24 * 365 * yeardif
			while (len(x) <= index):
				x.append(0)
			x[index] += entry[4] * entry[2]
	elif split == "day":
		for entry in c:
			yeardif = entry[3] / 10000000 - entry[3] / 10000000
			daydif = (entry[3] - (entry[3] / 10000000) * 10000000)  / 10000 - (start - (start / 10000000) * 10000000)  / 10000
			index = daydif + 365 * yeardif
			while (len(x) <= index):
				x.append(0)
			x[index] += entry[4] * entry[2]
	elif split == "month":
			yeardif = entry[3] / 10000000 - entry[3] / 10000000
			index = 365 * yeardif / 12;
			while (len(x) <= index):
				x.append(0)
			x[index] += entry[4] * entry[2]
	elif split == "year":
		for entry in c:
			yeardif = entry[3] / 10000000 - entry[3] / 10000000
			index = yeardif;
			while (len(x) <= index):
				x.append(0)
			x[index] += entry[4] * entry[2]
			plt.xlabel('Time (in ' + split + 's) from ')

	
	plt.bar(np.arange(index+1), x, color='r')
	plt.title('Total Post Influence Over Time')
	plt.ylabel('Total Post Value')
	plt.xlabel('Time (in ' + split + 's) ' + timeinterval)
	plt.savefig("time_vs_post_and_influence.png", format="png")
	plt.clf()
	c.close()

if __name__ == "__main__":
	if (len(sys.argv) != 5):
		print "\nGraph.py call should be of the form:"
		print "\tgraph.py <start> <end> <split> <database>"
		print "start and end are both numbers of the form YYDDDHHMM, where DDD is the day number out of 365. If you do not wish to input a start time and end time, make them 0."
		print "Split can be 'minute', 'hour', 'day', or 'year'.\n"
		print "Example use:"
		print "\tgraph.py 111142256 111212256 day myDatabase.db"
		print "This would create a bar graph in year 2011 between day 114 at the time 22:56 (April 24) and day 121 (May 1) at the time 22:56, with each day as a seperate bar, using data from myDatabase.db.\n"
		sys.exit()
	if (sys.argv[1] != '0'):
		start = int(sys.argv[1])
	else:
		start = 111142310
	if (sys.argv[2] != '0'):
		end = int(sys.argv[2])
	else:
		end = datetime.datetime.now().strftime("%y%j%H%M")
	split = sys.argv[3]
	if (split != 'minute' and split != "hour" and split != "day" and split != "month" and split != "year"):
		print "Invalid split. Must be 'minute', 'hour', 'day', 'month', or 'year'."
		sys.exit()
	
	graphall(sys.argv[1], int(start), int(end), split,sys.argv[4])
